package com.leyou.auth.web;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptiion.LyException;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.impl.AuthServiceImpl;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthController
 * @Date 2019/2/25 19:17
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Value("${ly.jwt.cookieName}")
    private String cookieName;

    @Autowired
    private AuthServiceImpl authService;
    
    @Autowired
    private JwtProperties prop;

    /**
     * 登陆，存入token到cookie
     *
     * @param username
     * @param password
     * @param request
     * @param response
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username, @RequestParam("password") String password,
            HttpServletRequest request, HttpServletResponse response) {
        //登陆
        String token = authService.login(username, password);
        //写入cookie
        CookieUtils.newBuilder(response).httpOnly().request(request).build(cookieName, token);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token, 
                                           HttpServletRequest request, HttpServletResponse response
    ) {
        try {
            //解析token
            UserInfo info = JwtUtils.getUserInfo(prop.getPublicKey(), token);
            //刷新cookie中的token
            String newToken = JwtUtils.generateToken(info, prop.getPrivateKey(), prop.getExpire());
            CookieUtils.newBuilder(response).httpOnly().request(request)
                    .build("LY_TOKEN", newToken);
            //已登录，返回用户信息
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }
}
